﻿using System;
using System.Data;
using System.Web.UI.WebControls;

namespace HiauPdm.Bll
{
    /// <summary>
    /// 主框架
    /// </summary>
    public class BMain
    {
        /// <summary>
        /// 登录验证
        /// </summary>
        public static string Login(string sUserName, string sPassword, out int oUserId, out string oRealName)
        {
            oUserId = 0;
            oRealName = string.Empty;
            if ((sUserName == null) || (sUserName == string.Empty))
            {
                return "未填写用户名，登录失败！";
            }
            sUserName = sUserName.ToLower();
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                DataSet dsUser = da.ExecuteQuery("SELECT ID,用户名,密码,姓名 FROM 用户列表 WHERE (用户名=@P0 OR 姓名=@P0) AND 状态=9", sUserName);
                if (dsUser == null)
                {
                    return "网络异常，登录失败！";
                }
                if (dsUser.Tables[0].Rows.Count != 1)
                {
                    return "用户不存在，登录失败！";
                }
                if (dsUser.Tables[0].Rows[0]["密码"].ToString() != BGlobal.Encrypt(sPassword, dsUser.Tables[0].Rows[0]["用户名"].ToString()))
                {
                    return "密码不正确，登录失败！";
                }
                oUserId = (int)dsUser.Tables[0].Rows[0]["ID"];
                oRealName = dsUser.Tables[0].Rows[0]["姓名"].ToString();
                da.Execute("INSERT INTO 系统日志(用户姓名,操作摘要) VALUES(@P0,@P1)", oRealName, "正常登录系统");
                return null;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        public static string ChangePwd(int iUserId, string sOldPwd, string sNewPwd, string sNewPwd2)
        {
            if (sNewPwd == string.Empty)
            {
                return "新密码不能为空，请输入新密码！";
            }
            if (sNewPwd != sNewPwd2)
            {
                return "您两次输入的新密码不一致，请重新输入！";
            }
            if (sNewPwd.Length < 6)
            {
                return "新密码不能过于简单，密码长度至少6位，建议字母与数字混合！";
            }
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                string sUserName = string.Empty;
                DataSet ds = da.ExecuteQuery("SELECT 用户名,姓名 FROM 用户列表 WHERE ID=@P0", iUserId);
                if ((ds != null) && (ds.Tables[0].Rows.Count == 1))
                {
                    sUserName = ds.Tables[0].Rows[0]["用户名"].ToString();
                }
                if (da.Execute("UPDATE 用户列表 SET 密码=@P2 WHERE ID=@P0 AND 密码=@P1", iUserId, BGlobal.Encrypt(sOldPwd, sUserName), BGlobal.Encrypt(sNewPwd, sUserName)) <= 0)
                {
                    return "修改登录密码失败，请确认您的旧密码输入是否正确！";
                }
                da.Execute("INSERT INTO 系统日志(用户姓名,操作摘要) VALUES(@P0,@P1)", ds.Tables[0].Rows[0]["姓名"].ToString(), "修改登录密码");
                return null;
            }
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        public static bool CheckAccess(string sModule, int iUserId)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                DataSet ds = da.ExecuteQuery("SELECT COUNT(1) FROM 模块列表 A,用户权限 B WHERE A.ID=B.模块ID AND (A.模块调用=@P0 OR A.模块名称=@P0) AND B.用户ID=@P1", sModule, iUserId);
                return ((ds != null) && (((int)ds.Tables[0].Rows[0][0]) > 0));
            }
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        public static DataSet GetChildMenu(int iMenuId, int iUserId)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                return da.ExecuteQuery("SELECT A.ID,A.模块名称,A.模块调用,A.ISJID FROM 模块列表 A,用户权限 B WHERE A.ID=B.模块ID AND A.模块调用 IS NOT NULL AND B.用户ID=@P0 AND ISNULL(A.ISJID,0)=@P1 ORDER BY A.模块编号", iUserId, iMenuId);
            }
        }

        /// <summary>
        /// 根据[上级模块列表ID]获得模块列表
        /// </summary>
        public static DataSet GetChildModule(int iMkLbId, int iUserId)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                return da.ExecuteQuery("SELECT A.ID,A.模块编号,A.模块名称,CAST(CASE WHEN B.ID IS NULL THEN 0 ELSE 1 END AS BIT) 模块选择 FROM 模块列表 A LEFT JOIN 用户权限 B ON A.ID=B.模块ID AND B.用户ID=@P0 WHERE A.模块锁定=0 AND ISNULL(A.ISJID,0)=@P1 ORDER BY A.模块编号", iUserId, iMkLbId);
            }
        }

        /// <summary>
        /// 根据[查询条件]查询人员
        /// </summary>
        public static DataSet QueryRy(string sWhere)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                return da.ExecuteQuery(string.Format("SELECT A.姓名,A.性别,A.备注 FROM 用户列表 A WHERE {0} ORDER BY A.姓名", BGlobal.BuildLike(sWhere, "A.姓名")));
            }
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        public static DataSet GetUsers()
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                return da.ExecuteQuery("SELECT ID,用户名,姓名,性别,联系电话,备注 FROM 用户列表 ORDER BY ID");
            }
        }

        /// <summary>
        /// 保存用户模块权限
        /// </summary>
        private static void SaveUserModule(int iUserId, TreeNode tn)
        {
            if (tn == null || tn.ChildNodes == null || tn.ChildNodes.Count <= 0) { return; }
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                for (int i = 0; i < tn.ChildNodes.Count; i++)
                {
                    if (tn.ChildNodes[i].Checked)
                    {
                        da.Execute("INSERT INTO 用户权限(用户ID,模块ID) SELECT @P0,@P1 FROM 用户列表 WHERE ID=@P0 AND NOT EXISTS(SELECT 1 FROM 用户权限 WHERE 用户ID=@P0 AND 模块ID=@P1)", iUserId, int.Parse(tn.ChildNodes[i].Value));
                    }
                    else
                    {
                        da.Execute("DELETE FROM 用户权限 WHERE 用户ID=@P0 AND 模块ID=@P1 AND 用户ID<>1", iUserId, int.Parse(tn.ChildNodes[i].Value));
                    }
                }
            }
            for (int i = 0; i < tn.ChildNodes.Count; i++)
            {
                SaveUserModule(iUserId, tn.ChildNodes[i]);
            }
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        public static string SaveUser(int iUserId, string sUser, string sRealName, string sSex, string sTel, string sBz, string sCzr, TreeNode tn)
        {
            if ((sUser.Trim() == string.Empty) || (sRealName.Trim() == string.Empty))
            {
                return "用户名、真实姓名不能为空！";
            }
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                if (iUserId > 0)
                {
                    if (da.Execute("UPDATE 用户列表 SET 姓名=@P2,性别=@P3,联系电话=@P4,备注=@P5 WHERE ID=@P0 AND 用户名=@P1", iUserId, sUser, sRealName, sSex, sTel, sBz) <= 0)
                    {
                        return "保存用户信息失败！";
                    }
                    SaveUserModule(iUserId, tn); // 保存用户权限
                    da.Execute("INSERT INTO 系统日志(用户姓名,操作摘要) VALUES(@P0,@P1)", sCzr, "编辑用户权限");
                }
                else
                {
                    if (da.Execute("INSERT INTO 用户列表(用户名,密码,姓名,性别,联系电话,备注,状态) VALUES(@P0,@P1,@P2,@P3,@P4,@P5,9)", sUser, BGlobal.Encrypt(string.Empty, sUser), sRealName, sSex, sTel, sBz) <= 0)
                    {
                        return "添加新用户失败！";
                    }
                    da.Execute("INSERT INTO 系统日志(用户姓名,操作摘要) VALUES(@P0,@P1)", sCzr, "添加登录用户");
                }
                return null;
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        public static string DelUser(int iUserId)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                da.Execute("DELETE FROM 用户权限 WHERE 用户ID=@P0 AND 用户ID<>1", iUserId);
                if (da.Execute("DELETE FROM 用户列表 WHERE ID=@P0 AND ID<>1", iUserId) <= 0)
                {
                    return "删除用户失败！";
                }
                return null;
            }
        }

        /// <summary>
        /// 清空用户密码
        /// </summary>
        public static string ResetPwd(int iUserId, string sUser, string sCzr)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                da.Execute("UPDATE 用户列表 SET 密码=@P2 WHERE ID=@P0 AND 用户名=@P1", iUserId, sUser, BGlobal.Encrypt(string.Empty, sUser));
                da.Execute("INSERT INTO 系统日志(用户姓名,操作摘要) VALUES(@P0,@P1)", sCzr, "清空用户密码");
            }
            return null;
        }

        /// <summary>
        /// 根据SQL语句获得DataSet
        /// </summary>
        public static DataSet GetDataSet(string pQueryCommand)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                return da.ExecuteQuery(pQueryCommand);
            }
        }

        /// <summary>
        /// 根据SQL语句获得DataSet
        /// </summary>
        public static DataSet GetDataSet(string pQueryCommand, params object[] pInParams)
        {
            using (DSql da = new DSql(BGlobal.DbConnString))
            {
                return da.ExecuteQuery(pQueryCommand, pInParams);
            }
        }
    }
}
